package it.unibo.util;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author ale
 * @version 1.0
 * @created 24-ott-2012 00:47:07
 */
public class Timer {

	private final int limit;
	private List<TimerEventListener> listeners;
	
	private Thread thread = null;
//	private int counter = 0;
//	private boolean stopped = false;

	private static int DEFAULT_LIMIT = 5000;
//	private static int SECOND = 1000;

	public Timer(){
		this(DEFAULT_LIMIT);
	}

	/**
	 * in millesecondi
	 * 
	 * @param limit
	 */
	public Timer(int limitTime){
		this.limit = limitTime;
		this.listeners = new CopyOnWriteArrayList<TimerEventListener>();
		this.thread = new Thread(new Runnable() {
			
			@Override
			public void run() 
			{	
				try {
					Thread.sleep(limit);
					fireTimerEvent();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
	}

	public int getLimit(){
		return limit;
	}

	@SuppressWarnings("deprecation")
	public void resetTimer(){
		thread.stop();
		thread.start();
//		counter = 0;
	}

	@SuppressWarnings("deprecation")
	public void stopTimer()
	{
		thread.stop();
//		stopped = true;
	}

	public void startTimer(){
		thread.start();
//		stopped = false;
//		try {
//			while((counter*SECOND) <= limit)
//			{
//				thread.wait(1000);
//				counter++;
//				if(stopped  == true)
//				{
//					break;
//				}
//			}
//			if(stopped  == false)
//				fireTimerEvent();
//		} catch (InterruptedException e) {
//			System.out.println("Timer wait exception");
//			e.printStackTrace();
//		}
	}

	/**
	 * 
	 * @param listener
	 */
	public void addTimerListener(TimerEventListener listener){
		listeners.add(listener);
	}

	public boolean isRunning()
	{
		return thread.isAlive();
	}
	
	/**
	 * 
	 * @param listener
	 */
	public void removeTimerListener(TimerEventListener listener){
		listeners.remove(listener);
	}

	protected void fireTimerEvent(){
		for (TimerEventListener timerListener : listeners) {
			timerListener.onTimerFired(new TimerEvent(this));
		}
	}

}